import * as fs from 'fs'
import * as path from 'path'

const writeToFile = (fileDir, fileName, content) => {
  return new Promise((resolve, reject) => {
    fs.mkdir(fileDir, { recursive: true }, (err, path) => {
      if (!err) {
        fs.writeFile(`${fileDir}/${fileName}`, content, 'utf8', (err) => {
          if (err) {
            console.error(err)
            reject(err)
          } else {
            resolve('')
          }
        })
      }
    })
  })
}

/**
 * 读取文件内容
 * @param {*} filePath
 * @returns
 */
const readFileContent = (filePath) => {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf8', (err, data) => {
      if (err) {
        console.error(err)
        reject(err)
      } else {
        resolve(data)
      }
    })
  })
}

/**
 * 是否为有效的路径
 * @param {*} filePath
 * @returns
 */
const isValidPath = (filePath) => {
  return new Promise((resolve, reject) => {
    fs.access(filePath, fs.constants.F_OK, (err) => {
      resolve(!err)
    })
  })
}

/**
 * 获取路径下的子目录和文件
 * @param {*} dir
 */
const findSubFiles = async (dir) => {
  return new Promise((resolve, reject) => {
    fs.readdir(dir, (err, files) => {
      if (err) {
        reject(err)
      } else {
        resolve(files)
      }
    })
  })
}

/**
 *  是否为文件
 * @param {*} filePath
 * @returns
 */
const isFile = (filePath) => {
  return new Promise((resolve, reject) => {
    fs.stat(filePath, (err, stats) => {
      if (err) {
        reject(err)
      } else {
        resolve(stats.isFile())
      }
    })
  })
}

/**
 *  是否为路径
 * @param {*} filePath
 * @returns
 */
const isDir = (filePath) => {
  return new Promise((resolve, reject) => {
    fs.stat(filePath, (err, stats) => {
      if (err) {
        reject(err)
      } else {
        resolve(stats.isDirectory())
      }
    })
  })
}

/**
 * 获取路径下指定后缀的文件列表
 * @param {*} dir
 * @param {*} extname
 * @returns
 */
const findSubFilesByExt = async (dir, extname) => {
  const subs = await findSubFiles(dir)
  return subs.filter((sub) => path.extname(sub) === `.${extname}`)
}

/**
 * 创建目录
 * @param {*} dir
 * @returns
 */
const mkdir = async (dir) => {
  return new Promise((resolve, reject) => {
    fs.mkdir(dir, { recursive: true }, (err) => {
      if (err) {
        reject(err)
      } else {
        resolve()
      }
    })
  })
}

/**
 * 删除文件
 * @param {string} filePath
 * @returns
 */
const removeFile = (filePath) => {
  return new Promise((resolve, reject) => {
    fs.unlink(filePath, (err) => {
      resolve(!!err)
    })
  })
}

export {
  writeToFile,
  isValidPath,
  isDir,
  readFileContent,
  findSubFiles,
  findSubFilesByExt,
  mkdir,
  removeFile
}
